#include "def_globales.h"
#include "ST7920.h"
#include "graphic.h"
#include "UART_routines.h"
#include "menu.h"
#include "SPI_routines.h"
#include "SD_routines.h"
#include "UART_routines.h"
#include "FAT32.h"
#include "adc.h"
unsigned char  error, data, FAT32_active;
unsigned int i;

unsigned char inicio_sd();
unsigned char muestras_automatic(int num_muestra);
void muestras_manual();
unsigned char cal_galga();
unsigned char cal_celda();
void port_init(void);

void modo_pc();

//declaracion variables
double Kg=0.0;//variable factor de galga
double Kp=0.0;//variable factor de puente
double Vp=0.0;//Variable Voltaje de puente
double Cal_p=0.0;//Variable Calibración Puente
double Cal_G=0.0;//variable Caliblación puente
unsigned int Tm=0;//variable Tiempo de muestras
unsigned int Nm=100;//variable numero de muestras
unsigned char flag_SD=0;

int main ()
{

    unsigned char tmp2[6];
    _delay_ms(500);
    port_init();

    flag_SD=    inicio_sd();
    lcd_init();
    Graphic_ON();
    ClearGraphics();
    TX_NEWLINE
    transmitString_F(PSTR("INICIALIZANDO BIENVENIDA"));
    TX_NEWLINE
    PutBMP(b);
    transmitString_F(PSTR("Universidad Nacional de Colombia \n Sede Bogota"));
    TX_NEWLINE
    transmitString_F(PSTR("Alimentacion"));
    TX_NEWLINE
    Vp=5.0*ReadChannel(chanel_4)/1024;
    dtostrf(Vp,2,5,tmp2);
    transmitString(tmp2);
    TX_NEWLINE

    sleep(2000);
    Local_Code_Clear();
    ClearGraphics();
    PutBMP(un);
    sleep(4000);

    if(flag_SD==1){
        menu_SD_Detect();
        while(1);
        }
     if(flag_SD==2){
        menu_FAT32_Detect();
        while(1);
        }


    while(1)
    {
        Tm=0;
        switch(menu_principal())
        {
        case '1':
        {

            transmitString_F(PSTR("Modo Automatico"));
            TX_NEWLINE
            Kg= menu_factor_galga();
            transmitString_F(PSTR("factor de galga"));
            TX_NEWLINE
            dtostrf(Kg,2,5,tmp2);
            transmitString(tmp2);
            TX_NEWLINE
            Kp=menu_factor_puente();
            transmitString_F(PSTR("factor de puente"));
            TX_NEWLINE
            dtostrf(Kp,2,5,tmp2);
            transmitString(tmp2);
            TX_NEWLINE
            transmitString_F(PSTR("Tiempo de muestreo"));
            TX_NEWLINE
            while(Tm==0)Tm=menu_tm();
            itoa(Tm,tmp2,10);
            transmitString(tmp2);
            TX_NEWLINE
            transmitString_F(PSTR("Numero de muestras"));
            TX_NEWLINE
            Nm=numero_de_muestras();
            itoa(Nm,tmp2,10);
            transmitString(tmp2);
            TX_NEWLINE
            while(menu_getName());
            transmitString(fileName);
            TX_NEWLINE
            convertFileName(fileName);
            transmitString(fileName);
            TX_NEWLINE
            cal_galga();
            cal_celda();
            muestras_automatic(Nm);

            break;

        }

        case '2':
        {

            transmitString_F(PSTR("Modo Manual"));
            TX_NEWLINE
            Kg= menu_factor_galga();
            transmitString_F(PSTR("factor de galga"));
            TX_NEWLINE
            dtostrf(Kg,0,5,tmp2);
            transmitString(tmp2);
            TX_NEWLINE
            while(menu_getName());
            transmitString(fileName);
            TX_NEWLINE
            convertFileName(fileName);
            transmitString(fileName);
            TX_NEWLINE
            muestras_manual();

            break;
        }
        case '3':
        {
            modo_pc();
            break;
        }
        default:
            menu_error();
            break;
        }

    }

    while(1)
    {
        PORTB |= (1<<PB3);
        _delay_ms(500);
        PORTB  &= ~(1<<PB3);
        _delay_ms(500);

    }
    return 0;
}
void port_init(void)
{
    DDRC=0xFF;
    asm volatile ("NOP");
    DDRD=0XFF;
    asm volatile ("NOP");
    DDRB  = 0xB1;
    asm volatile ("NOP");
    uart0_init();
    asm volatile ("NOP");
    spi_init();

}

unsigned char inicio_sd()
{

    cardType = 0;
    for (i=0; i<10; i++)
    {
        error = SD_init();
        if(!error) break;
    }
    if(error)
    {
        if(error == 1) transmitString_F(PSTR("SD card not detected.."));
        if(error == 2) transmitString_F(PSTR("Card Initialization failed.."));

        return 1;
    }


    switch (cardType)
    {
    case 1:
        transmitString_F(PSTR("Standard Capacity Card (Ver 1.x) Detected!"));
        break;
    case 2:
        transmitString_F(PSTR("High Capacity Card Detected!"));
        break;
    case 3:
        transmitString_F(PSTR("Standard Capacity Card (Ver 2.x) Detected!"));
        break;
    default:
        transmitString_F(PSTR("Unknown SD Card Detected!"));
        break;
    }
    SPI_HIGH_SPEED;
    _delay_ms(1);

    FAT32_active = 1;
    error = getBootSectorData (); //read boot sector and keep necessary data in global variables
    if(error)
    {
        TX_NEWLINE;
        transmitString_F (PSTR("FAT32 not found!"));  //FAT32 incompatible drive
        FAT32_active = 0;
        return 2;
    }

    return 0;

}
unsigned char muestras_automatic(int num_muestra)
{
    unsigned char voltaje[7];
    float ch1=0.0;
    float ch2=0.0;
    unsigned char i=0;
    clr_lcd();
    Local_Code_Clear();
    Graphic_ON();
    ClearGraphics();
    Draw_Rectangle(0,0,64,128);
    Graphic_OFF();
    print(0,1," AUTOMATICO  ");
    while(num_muestra)
    {

        i=0;

        ch1 =  5.0*ReadChannel(chanel_0)/1024-Cal_p;
        ch2 =  5.0*ReadChannel(chanel_3)/1024 - Cal_G;
        print(0,2,"                ");
        print(0,2,"EF: ");
        dtostrf( ch1, 0, 5, voltaje);
        for(i=0; i<7; i++)
        {
            dataString[i]=voltaje[i];
            send_data(voltaje[i]);
        }
        dataString[i++]='\t';
        print(0,3,"                ");
        print(0,3,"DEFN: ");
        dtostrf( ch2, 0,5, voltaje );
        for(; i<15; i++)
        {
            dataString[i]=voltaje[i-8];
            send_data(voltaje[i-8]);

        }

        dataString[i++]='\n';
        dataString[i]='~';
        writeFile(fileName);
        sleep(Tm-50);
        num_muestra=num_muestra-1;
    }



    return 0;
}
void muestras_manual()
{

    unsigned char tmp[7];
    unsigned char tmp2[7];
    float ch1=0.0;
    unsigned char i=0,j=0;
    unsigned char dat=0;
    double fuerza;
    clr_lcd();
    Local_Code_Clear();
    Graphic_ON();
    ClearGraphics();
    Draw_Rectangle(0,0,64,128);
    Graphic_OFF();
    print(0,1," MANUAL  ");
    print(0,4,"A=OK B=X C=CLEAR");
    while(1)
    {
        print(0,3,"                ");
        print(0,2,"                ");
        print(0,3,"D= ");
        print(0,2,"F= ");

        for(i=0; i<7; i++)tmp[i]=0;
        i=0;
        j=0;
        while(i<8)
        {
            dat=key_read();
            if(dat=='C')
            {
                print(0,2,"                ");
                print(0,2,"F= ");
                i=0;
                continue;
            }
            if(dat=='A')break;//enter
            if(dat=='*')dat='.';
            if(dat=='#')continue;
            if(dat=='B')return;
            if(dat=='D')continue;
            tmp[i]=dat;
            send_data(dat);
            i++;
        }
        transmitString(tmp);
        TX_NEWLINE
        fuerza=atof(tmp);
        dtostrf(fuerza, 0, 5,tmp2);
        for(j=0; j<7; j++)
        {
            dataString[j]=tmp2[j];
        }
        dataString[j++]='\t';
        print(0,3,"                ");

        print(0,3,"D= ");
        ch1 =  5.0*ReadChannel(chanel_3)/1024;
        dtostrf( ch1, 0,5, tmp2);
        for(; j<15; j++)
        {
            dataString[j]=tmp2[j-8];
            send_data(tmp2[j-8]);

        }
        dataString[j++]='\n';
        dataString[j]='~';
        writeFile(fileName);
        sleep(500);

    }
}
unsigned char cal_galga()
{

    unsigned char voltaje[7];
    clr_lcd();
    Local_Code_Clear();
    Graphic_ON();
    ClearGraphics();
    Draw_Rectangle(0,0,64,128);
    Graphic_OFF();
    do
    {
        Cal_G=5.0*ReadChannel(chanel_3)/1024;
        dtostrf(Cal_G, 0, 5, voltaje);
        clr_lcd();
        print(0,1,"      CERO      ");
        print(0,2," GALGA: ");
        print(0,3,voltaje);
        print(0,4,"A=OK  C=CLEAR");
    }
    while(key_read()!='A');

    return 0;


}
unsigned char cal_celda()
{

    unsigned char voltaje[7];
    clr_lcd();
    Local_Code_Clear();
    Graphic_ON();
    ClearGraphics();
    Draw_Rectangle(0,0,64,128);
    Graphic_OFF();
    do
    {
        Cal_p=5.0*ReadChannel(chanel_0)/1024;
        dtostrf(Cal_p, 0, 5, voltaje);
        clr_lcd();
        print(0,1,"      CERO      ");
        print(0,2," CELDA DE CARGA: ");
        print(0,3,voltaje);
        print(0,4,"A=OK  C=CLEAR");
    }
    while(key_read()!='A');

    return 0;


}
//void muestras_pc()
void modo_pc(){

double x=0.0;
double y=0.0;
double deltay=6.0;
unsigned char data;
unsigned char voltajex[7];
unsigned char voltajey[7];
unsigned char tempo[16];
unsigned char j=0;
    clr_lcd();
    Local_Code_Clear();
    Graphic_ON();
    ClearGraphics();
    Draw_Rectangle(0,0,64,128);
    Graphic_OFF();
    print(0,3,"Modo PC");

while(1){
    j=0;
    for(j=0;j<7;j++){voltajex[j]=0;voltajey[j]=0;}

    data=receiveByte();

    if(data==0x40){return ;}
    if(data==0x0A){
   x=x+10.0;
   dtostrf(x,0,6, voltajex);
   transmitString(voltajex);
   transmitString("\t");
   if(y>50)deltay=1.0;
   if(y>150)deltay=0.5;
   if(y>200)deltay=0.1;
   y=y+deltay;
   dtostrf(y,0,6,voltajey);


   transmitString(voltajey);
   transmitString("\n");
 // transmitString("234\t25\n");

}


}






}
